var search = function () {

    var shopId = function () {
        return $('#shop').val();
    };

    var keyword = function () {
        return $('.search-input').val();
    };

    var searchBtn = function () {
        $('.search-btn').on('click',function () {
            window.location.href = "/search/" + shopId() + "?keyword=" + keyword();
        });
    };

    var setWordList = function () {
        var searchWords = getSearchWords();
        if ($('#isFirst').length) {
            //表示是初始化的页面,将locationStorage中的数据写到页面
            var listWordsDiv = $('.search-tag');
            if(!searchWords.length){
                listWordsDiv.append('<div class="emptyMsg"><div class="empty-Search"></div></div>');
                $('.search-clear').hide();
                return
            }
            var listStr = '';
            for(var i = 0; i < searchWords.length; i++){
                listStr += '<a class="am-round am-text-center search-word white-background am-margin-xs">'+ searchWords[i] +'</a>'
            }
            listWordsDiv.append(listStr);
            $('.search-tag ').delegate('.search-word', 'click', function () {
                keywords = $(this).text();
                window.location.href = "/search/"+ shopId() +"?keyword=" + keywords;
            });
        }else{
            //表示搜索有结果,这个时候我们要将结果写入
            if(!searchWords.length){
                localStorage.setItem('searchHistory',JSON.stringify([keyword()]));
            }else{
                if(searchWords.join("_").indexOf(keyword()) == -1){
                    searchWords.push(keyword());
                    localStorage.setItem('searchHistory',JSON.stringify(searchWords));
                }
            }
        }
    };

    var clearHistoty = function () {
      $('.removeSearchList').click(function () {
          localStorage.removeItem('searchHistory');
          window.location.reload();
      })
    };


    var getSearchWords = function () {
        //localStorage.setItem("searchHistory",JSON.stringify(['hahh',"hdasfijalfj"]));
        var searchStr = localStorage.getItem("searchHistory");
        return  searchStr ? JSON.parse(searchStr) : [];
    };

    var keyListen = function () {
        var input = $(".search-input");
        input.on('keydown', function (e) {
            var key = e.which;
            if (key == 13) {
                window.location.href = "/search/"+ shopId() +"?keyword=" + keyword();
            }
        });
    };
    var isLoading = false;
    var addToCart = function () {
        $('.am-container').delegate('.add-cart','click',function(){
            var userToken = getUserLoginStatus(true);
            if (userToken) {
                //获取商品ID
                var productId = $(this).attr('data-productId');
                if (!productId) {
                    messageBox("获取商品ID失败");
                    return;
                }
                if(isLoading){
                    messageBox("不要太心急~慢慢来");
                    return;
                }
                //请求接口,获取结果
                isLoading = true;
                apiRequest('POST', '/cart', {product: productId, productCount: 1,userId:userToken}).then(function (results) {
                    isLoading = false;
                    if (results.code == 200) {
                        console.log(results);
                        messageBox('添加成功啦，快去购物车查看吧');
                    } else {
                        if(results.code == 102){
                            doLogin();
                            return;
                        }
                        messageBox(results.message);
                    }
                }, function (err, error) {
                    isLoading = false;
                    console.log(err, error);
                    messageBox("网络错误");
                })
            } else {
                doLogin();
            }
        })
    };

    return {
        init: function () {
            searchBtn();
            setWordList();
            keyListen();
            clearHistoty();
            addToCart();
        }
    }
}();

